<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row :gutter="16" class="query-form2" v-show="!switchFlag">
        <Col span="8">
          <FormItem label="活动方案名称：" prop="programmeName">
            <Input class="query-form-el" type="text" v-model="form1.programmeName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="活动主题名称：" prop="activityName">
            <Input class="query-form-el" type="text" v-model="form1.themeName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">
              展开
              <Icon type="ios-arrow-down"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="活动方案名称：" prop="activityName">
            <Input class="query-form-el" type="text" v-model="form1.programmeName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="活动主题名称：" prop="activityName">
            <Input class="query-form-el" type="text" v-model="form1.themeName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="主办单位：" prop="themeAddress">
            <Input class="query-form-el" type="text" v-model="form1.themeAddress"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="8">
          <FormItem label="活动时间：">
            <Date-picker type="daterange" style="width: 95%" v-model="activityDate"/>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="编制人员：" prop="staffName">
            <Input class="query-form-el" type="text" v-model="form1.staffName"></Input>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="负责人：" prop="possess">
            <Input class="query-form-el" type="text" v-model="form1.possess"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16" v-show="switchFlag" class="query-form2">
        <Col span="24">
          <div style="float: right;height:44px">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2"
                    type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <DownloadButton :api="exportUrl" :export-form-before="exportBefore" :query-form="form1"></DownloadButton>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable" @on-sort-change="sortChange">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :title="title" :transfer=false :mask-closable="false" v-model="model1" :width=981>
      <Row>
        <Col span="24">
          <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="11">
                <FormItem label="活动方案名称：" prop="programmeName">
                  <Input type="text" v-model="form1datacopy.programmeName"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="活动主题：" prop="themeName">
                  <Input type="text" v-model="form1datacopy.themeName"></Input>
                </FormItem>
              </Col>
              <!--  <Col span="7" >
                  <FormItem label="编制日期：" prop="preparationDate">
                      <DatePicker v-model="form1datacopy.preparationDate" type="date" placeholder="请输入" ></DatePicker>
                  </FormItem>
              </Col>-->

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="5">
                <FormItem label="开始时间：" prop="startDate">
                  <DatePicker v-model="form1datacopy.startDate" type="date"
                              placeholder="请输入"></DatePicker>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="结束时间：" prop="endDate">
                  <DatePicker v-model="form1datacopy.endDate" type="date"
                              placeholder="请输入"></DatePicker>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="负责人：" prop="possess">
                  <Input type="text" v-model="form1datacopy.possess"></Input>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="联系方式：" prop="phone">
                  <Input type="text" v-model="form1datacopy.phone"></Input>
                </FormItem>
              </Col>


              <!--<Col span="7" >
                  <FormItem label="上报单位：" prop="reportingUnit">
                      <cascaderDom class="query-form-el" style="padding-top: 4px" ref="reportingUnit"  @setOrgInfo="setPeportingUnitId" @setOrgName="setPeportingUnitName"  :currentOrgId = "reportingUnit"
                                   :currentOrgName = "reportingUnitName"   :orgTree = "true"  ></cascaderDom>
                  </FormItem>
              </Col>-->
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <!--  <Col span="7">
                    <FormItem label="上报日期：" prop="reportingDate">
                        <DatePicker v-model="form1datacopy.reportingDate" type="date" placeholder="请输入" ></DatePicker>
                    </FormItem>
                </Col>-->
              <Col span="11">
                <FormItem label="主办单位：" prop="themeAddress">
                  <Input v-model="form1datacopy.themeAddress" type="text"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="编制人员：" prop="staff">

                  <Input v-model="form1datacopy.staffName" readonly type="text"/>
                </FormItem>

              </Col>


              <!--   <Col span="5">
                     <FormItem label="审核人员：" prop="auditor">

                         <Select
                                 placeholder="请输入姓名后选择"
                                 v-model="form1datacopy.auditor"
                                 filterable
                                 :remote-method="remoteMethod1"
                                 :loading="loading1">
                             <Option v-for="(option, index) in options1" :value="option.userId"
                                     :label="option.userName" :key="index">
                                 <span>{{option.userName}}</span>
                                 <span style="float:right;color:#ccc">{{option.orgInfo.orgName}}</span>
                             </Option>
                         </Select>
                     </FormItem>
                 </Col>
                 <Col span="5">
                     <FormItem label="批准人员：" prop="approvedBy">
                         <Select
                                 placeholder="请输入姓名后选择"
                                 v-model="form1datacopy.approvedBy"
                                 filterable
                                 :remote-method="remoteMethod1"
                                 :loading="loading1">
                             <Option v-for="(option, index) in options1" :value="option.userId"
                                     :label="option.userName" :key="index">
                                 <span>{{option.userName}}</span>
                                 <span style="float:right;color:#ccc">{{option.orgInfo.orgName}}</span>
                             </Option>
                         </Select>
                     </FormItem>
                 </Col>-->
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="描述：" prop="desc">
                  <Input v-model="form1datacopy.desc" type="textarea" :rows="2"/>
                </FormItem>
              </Col>

            </Row>
            <!--  <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="23">
                      <FormItem label="封面：" prop="cover">
                          <Upload
                                  ref="upload"
                                  type="drag"
                                  :show-upload-list="true"
                                  :before-upload="beforeUploadCover"
                                  accept="image/jpg, image/jpeg,image/png,image/gif,image/bmp"
                                  :action="upUrl"
                                  :max-size="1024000">
                              <div style="padding: 0px 0;height: 70px">
                                  <Icon type="ios-cloud-upload" size="40" style="color: #3399ff"></Icon>
                                  <p> 请上传 jpg，png 格式的图片，大小不超过5MB</p>
                              </div>
                          </Upload>
                          <div v-if="coverName !== null">
                              附件： <a @click.prevent="downloadFile(fileId,fileName)">{{coverName}}</a>
                              <Button type="text" icon="md-trash" @click="deleteCover(form1datacopy.cover)"
                                      style="margin-left: 20px;margin-bottom: 3px"/>
                          </div>
                      </FormItem>
                  </Col>
              </Row>-->
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="方案附件：" prop="whetherVote">
                  <Upload
                      ref="upload"
                      type="drag"
                      :show-upload-list="true"
                      :before-upload="beforeUpload"
                      :action="upUrl"
                      :max-size="1024000"
                  >
                    <div style="padding: 0px 0;height: 70px">
                      <Icon type="ios-cloud-upload" size="40" style="color: #3399ff"></Icon>
                      <p> 请上传大小不超过5MB的文件</p>
                    </div>
                  </Upload>
                  <div v-if="fileName !== null">
                    附件： <a @click.prevent="downloadFile(fileId,fileName)">{{ fileName }}</a>
                    <Button type="text" icon="md-trash"
                            @click="deleteFile(form1datacopy.programmeFile)"
                            style="margin-left: 20px;margin-bottom: 3px"/>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button @click="submit('form1datacopy')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal title="活动方案详情" class="modal-view-detail" :transfer=false v-model="model2" :width=1000>
      <Row>
        <Col span="24">
          <Form :model="showdata" :label-width="160">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="活动方案名称：" prop="programmeName">
                  {{ showdata.programmeName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="编制日期：" prop="preparationDate">
                  {{ showdata.preparationDate }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="活动主题：" prop="themeName">
                  {{ showdata.themeName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="负责人：" prop="possess">
                  {{ showdata.possess }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="联系方式：" prop="phone">
                  {{ showdata.phone }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="主办单位：" prop="themeAddress">
                  {{ showdata.themeAddress }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="开始时间：" prop="startDate">
                  {{ showdata.startDate }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="结束时间：" prop="endDate">
                  {{ showdata.endDate }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="编制人员：" prop="staffName">
                  {{ showdata.staffName }}
                </FormItem>
              </Col>
              <Col span="11">

              </Col>
              <!--     <Col span="11">
                       <FormItem label="审核人员：" prop="auditorName">
                           {{showdata.auditorName}}
                       </FormItem>
                   </Col>-->
              <!--                            <Col span="11">
                                              <FormItem label="上报单位：" prop="whetherComments">
                                                  {{showdata.orgName}}
                                              </FormItem>
                                          </Col>-->
            </Row>
            <!--                        <Row type="flex" justify="space-around" class="code-row-bg">
                                     &lt;!&ndash;   <Col span="11">
                                            <FormItem label="批准人员：" prop="approvedByName">
                                                {{showdata.approvedByName}}
                                            </FormItem>
                                        </Col>&ndash;&gt;

                                        <Col span="11">
                                            <FormItem label="上报日期：" prop="reportingDate">
                                                {{showdata.reportingDate}}
                                            </FormItem>
                                        </Col>
                                        <Col span="11">

                                        </Col>
                                    </Row>-->

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="描述：" prop="desc">
                  {{ showdata.desc }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="23">
                <FormItem label="方案附件：" prop="programmeFile">
                  <a @click.prevent="downloadFile(fileId,fileName)">{{ fileName }}</a>
                </FormItem>
              </Col>
            </Row>
            <!-- <Row type="flex" justify="space-around" class="code-row-bg">
                 <Col span="23">
                     <FormItem label="封面：" prop="coverId">
                         <a @click.prevent="downloadFile(coverId,coverName)">{{coverName}}</a>
                     </FormItem>
                 </Col>
             </Row>-->
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
    <Modal :transfer=false v-model="model3" :width=900>
      <Tabs>
        <TabPane label="历史记录">
          <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                 :loading="loading2"
                 :data="history" width="100%" :height="450" highlight-row stripe size="small"></Table>
        </TabPane>
        <TabPane label="流程图">
          <div style="height: 450px; overflow-y: auto; overflow-x: auto">
            <img :src="imgUrl">
          </div>
        </TabPane>
      </Tabs>
      <div slot="footer">
        <Button @click="model3=false" class="ivu-btn-save">关闭</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import cascaderDom from "../../../../components/cascader-dom.vue"
import {sessionStorage} from '../../../../common/cacheUtils.js';
import {Api} from '../../../../api/index.js'
import DownloadButton from '@/components/download-button';

export default {
  components: {
    cascaderDom, DownloadButton
  },
  data() {
    return {
      exportUrl: Api.exportProgramme,
      history: [],
      loading2: false,
      model3: false,
      options1: [],
      buttonLoading: false,
      loading: false,
      title: "",
      activityDate: ['', ''],
      saveMod: false,
      upUrl: Api.uploadMongoFile,
      switchFlag: false,
      form1: {},
      setCurrentName: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      setStaff: {},
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      imgUrl: '',
      columns2: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
        },
        {
          width: 180,
          title: '审批时间',
          key: 'endTime',
          align: 'center',
        },
        {
          width: 185,
          title: '节点名称',
          key: 'name',
          align: 'center',
        },
        {
          width: 120,
          title: '审批人',
          key: 'userName',
          align: 'center'
        },
        {
          width: 100,
          title: '审批意见',
          key: 'route',
          align: 'center'
        },
        {
          width: 200,
          title: '备注',
          key: 'opinions',
          align: 'center'
        },
      ],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        /*         {
                     title: '状态',
                     align: 'center',
                     key: 'status',
                     minWidth: 100,
                     render: (h, params) => {
                         let color = 'green';
                         if (params.row.procinstState == undefined || params.row.procinstState == null || params.row.procinstState == 2) {
                             color = 'red';
                         }
                         return h('div', [
                             h('span', {
                                 style: {
                                     color: color
                                 }
                             }, params.row.procinstState == 1 ? '审批中' : params.row.procinstState == 2 ? '被退回' : params.row.procinstState == 3 ? '审批通过' : '未上报' || '--')
                         ]);
                     }
                 },*/
        {
          minWidth: 150,
          title: '活动方案名称',
          align: 'center',
          key: 'programmeName',
        },
        {
          minWidth: 150,
          title: '主题名称',
          align: 'center',
          key: 'themeName',
        },
        {
          minWidth: 150,
          title: '负责人',
          align: 'center',
          key: 'possess',
        },
        {
          minWidth: 150,
          title: '联系方式',
          align: 'center',
          key: 'phone',
        },
        {
          minWidth: 300,
          title: '主办单位',
          align: 'center',
          key: 'themeAddress',
        },

        {
          minWidth: 150,
          title: '开始时间',
          align: 'center',
          key: 'startDate',
          sortable: "custom",
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.startDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '结束时间',
          align: 'center',
          key: 'endDate',
          sortable: "custom",
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.endDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '编制日期',
          align: 'center',
          key: 'preparationDate',
          sortable: "custom",
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.preparationDate), 'yyyy-MM-dd'))
            ]);
          }
        },

        {
          minWidth: 150,
          title: '编制人员',
          align: 'center',
          key: 'staffName',
        },
        /*   {
               minWidth: 150,
               title: '审核人员',
               align: 'center',
               key: 'auditorName',
           },
           {
               minWidth: 150,
               title: '批准人员',
               align: 'center',
               key: 'approvedByName',
           },*/
        /*{
            minWidth: 150,
            title: '上报单位',
            align: 'center',
            key: 'orgName',
        },*/
        /*{
            minWidth: 150,
            title: '上报日期',
            align: 'center',
            key: 'reportingDate',
            render: (h, params) => {
                return h('div', [
                    (this.formatDate(new Date(params.row.reportingDate), 'yyyy-MM-dd'))
                ]);
            }
        },*/
        {
          minWidth: 300,
          title: '描述',
          align: 'center',
          key: 'desc',
          ellipsis: true
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            if (params.row.isSubmit == "1") {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px'
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                }, '删除'),
              ]);
            } else {
              if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                  || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
                return h('div', [
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 1);
                      }
                    }
                  }, '详情'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px',
                      color: '',
                    },
                    on: {
                      click: () => {
                        this.showData(params, 2);
                      }
                    }
                  }, '修改'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px',
                      color: 'red',
                    },
                    on: {
                      click: () => {
                        this.$Modal.confirm({
                          title: '数据删除',
                          content: '<p>确定删除该条信息</p>',
                          okText: '确认',
                          onOk: () => {
                            this.deleteData(params);
                          },
                          cancelText: '取消'
                        });
                      }
                    }
                  }, '删除'),
                ]);
              } else {
                return h('div', [
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px'
                    },
                    on: {
                      click: () => {
                        this.showData(params, 1);
                      }
                    }
                  }, '详情'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {type: 'primary', size: 'small'},
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '修改'),
                  h('Divider', {
                    props: {
                      type: 'vertical',
                    }
                  }, ''),
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {fontSize: '14px', color: '#c5c8ce', pointerEvents: 'none'}
                  }, '删除'),
                ]);
              }

            }

          }
        }
      ],
      ruleCustom: {
        programmeName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        possess: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        themeName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(' ');
              this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        startDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        endDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        themeAddress: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        preparationDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

        auditor: [{
          required: true,
          message: '  ',
          trigger: 'change'
        }],
        approvedBy: [{
          required: true,
          message: '  ',
          trigger: 'change'
        }],
        peportingUnit: [{
          required: true,
          message: '  ',
          trigger: 'change'
        }],
        peportingDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      form1datacopy: {},
      dataTable: [],
      showdata: {},
      setApprovedBy: {},
      setAuditor: {},
      coverId: null,
      fileId: null,
      model1: false,
      model2: false,
      add: false,
      tableHeight: 10,
      file: null,
      fileName: null,
      coverName: null,
      downloadUrl: Api.downloadMongoFile,
      themeList: [],
      reportingUnitName: '',
      reportingUnit: '',
    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
    this.selectThemeList();

  },
  methods: {
    exportBefore(data) {
      let orgId = sessionStorage('userId').getObject('userId').companyId
      data['orgId'] = orgId;
      data['activityType'] = this.$route.query.type;
      if (this.activityDate[0] != "" && this.activityDate[1] != "") {
        data['startDate'] = this.formatDate(new Date(this.activityDate[0]), 'yyyy-MM-dd');
        data['endDate'] = this.formatDate(new Date(this.activityDate[1]), 'yyyy-MM-dd');
      }
    },
    downloadFile(fileId, fileName) {
      let url = this.downloadUrl + "/" + fileId
      this.$http.get(url, {
        responseType: 'blob' //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.body.type //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 88;
      } else {
        this.tableHeight = this.tableHeight + 88;
      }
    },
    sortChange(data) {
      if (data.order === 'asc' || data.order === 'desc') {
        let order = data.key
        this.form1.dynamicSort = order + ' ' + data.order
        this.query()
      }
    },
    beforeUpload(file) {
      let _this = this;
      const files = file;
      let formData = new FormData();
      formData.append("file", files);
      this.$http.put(Api.uploadMongoFile, formData).then((res) => {
        if (res.data.result == "success") {
          _this.form1datacopy.programmeFile = res.data.id;
          _this.getFiles();
        } else {
          this.$Message.error("附件上传失败");
        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });

      return false;
    },
    deleteFile(id) {
      this.$http.delete(Api.uploadMongoFile + "/" + id).then((res) => {
        console.log(id);
        if (res.data.result == "success") {
          this.form1datacopy.programmeFile = null;
          this.fileName = null;

        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });
    },
    deleteCover(id) {
      this.$http.delete(Api.uploadMongoFile + "/" + id).then((res) => {
        console.log(id);
        if (res.data.result == "success") {
          this.form1datacopy.cover = null;
          this.coverName = null;
        }
      }).catch(e => {
        this.$Message.error("附件上传失败");
      });

    },
    setUserName(data) {
      this.form1.userName = data;
    },
    setUserId(data) {
      this.form1.staff = data[data.length - 1];
    },
    selectThemeList() {
      let data = {
        currentPage: 1,
        size: 100
      }

      let url = Api.queryActivityTheme;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.themeList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    cancel() {
      this.form1 = {};
      this.activityDate = ['', ''];
      this.query1();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },

    showData(data, flag) {
      this.buttonLoading = false;
      this.fileId = null;
      this.coverId = null;
      this.fileName = null;
      this.coverName = null;
      if (flag == 1) {
        //查看页面
        this.showdata = data.row;
        this.showdata.preparationDate = this.formatDate(new Date(this.showdata.preparationDate), 'yyyy-MM-dd');
        if (this.showdata.reportingDate != null) {
          this.showdata.reportingDate = this.formatDate(new Date(this.showdata.reportingDate), 'yyyy-MM-dd');

        }

        this.showdata.startDate = this.formatDate(new Date(this.showdata.startDate), 'yyyy-MM-dd');
        this.showdata.endDate = this.formatDate(new Date(this.showdata.endDate), 'yyyy-MM-dd');

        this.$http.get(Api.getPTWSchemeFile + "/" + this.showdata.cover).then((res) => {
          this.coverId = res.data.id;
          this.coverName = res.data.fileName;

        }).catch(e => {
          this.$Message.error("数据获取失败")
        });
        this.model2 = true;

      } else {
        //修改页面
        this.options1.push({userId: data.row.staff, userName: data.row.staffName, orgInfo: {orgName: ''}});
        this.options1.push({
          userId: data.row.auditor,
          userName: data.row.auditorName,
          orgInfo: {orgName: ''}
        });
        this.options1.push({
          userId: data.row.approvedBy,
          userName: data.row.approvedByName,
          orgInfo: {orgName: ''}
        });
        this.title = "活动方案修改";
        this.saveMod = false;
        this.fileName = null;
        this.coverName = null;
        this.reportingUnitName = data.row.orgName;
        this.reportingUnit = data.row.reportingUnit;
        this.setApprovedBy = {
          value: data.row.approvedBy,
          label: data.row.approvedByName
        };
        this.setAuditor = {
          value: data.row.auditor,
          label: data.row.auditorName
        };
        this.setStaff = {
          value: data.row.staff,
          label: data.row.staffName
        };
        this.add = false;
        this.form1datacopy = data.row;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.$http.get(Api.getPTWSchemeFile + "/" + this.form1datacopy.programmeFile).then((res) => {
          if (res.data.result == 'success') {
            this.fileId = res.data.id;
            this.fileName = res.data.fileName;
          }

        }).catch(e => {
          this.$Message.error("数据获取失败")
        });
        this.$http.get(Api.getPTWSchemeFile + "/" + this.form1datacopy.cover).then((res) => {
          if (res.data.result == 'success') {
            this.coverId = res.data.id;
            this.coverName = res.data.fileName;
          }


        }).catch(e => {
          this.$Message.error("数据获取失败")
        });
        this.model1 = true;
      }
    },

    getSelectRows(rows) {
      this.deleteRows = rows;
    },

    deleteData(params) {
      let url = Api.deleteProgramme;
      this.$http.delete(url + '/' + params.row.programmeId).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })

    },
    getFiles() {
      let _this = this;
      this.$http.get(Api.getPTWSchemeFile + "/" + _this.form1datacopy.programmeFile).then((res) => {
        debugger;
        _this.fileId = res.data.id;
        _this.fileName = res.data.fileName;

      }).catch(e => {
        this.$Message.error("数据获取失败")
      });
    },
    remoteMethod1(query) {
      if (query !== '') {
        clearTimeout(this.remoteMethod1.timer);
        this.remoteMethod1.timer = setTimeout(() => {
          this.options1.splice(0, this.options1.length);
          this.loading1 = true;
          let data = {
            userName: query,
            orgId: sessionStorage('userId').getObject('userId').companyId
          };
          this.$http.get(Api.queryUserByUserName, {params: data}).then((res) => {
            this.loading1 = false;
            res.data.data.forEach(item => {
              this.options1.push(item);
            })

          }).catch(e => {
            this.loading1 = false;
          })
        }, 200);
      } else {
        this.options1 = [];
      }
    },
    showHistory(row) {
      this.model3 = true;
      this.loading2 = true;
      this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
        this.history = res.data;
        this.loading2 = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    query1() {
      this.pagedata.currentPage = 1;
      this.query()
    },
    query() {
      this.loading = true;
      let orgId = sessionStorage('userId').getObject('userId').companyId
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: orgId,
        activityType: this.$route.query.type

      };
      if (this.activityDate[0] != "" && this.activityDate[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.activityDate[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.activityDate[1]), 'yyyy-MM-dd');
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryProgramme;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.loading = false;
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    reset() {
      this.activityDate = ['', ''];
      this.form1 = {}
      setTimeout(() => {
        this.$refs.childUser.setCurrentUser();
      }, 50)

    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    /* submit(name) {
        this.$refs[name].validate((valid) => {
            if (valid) {
               this.form1datacopy.startDate = this.formatDate(new Date(this.form1datacopy.startDate), 'yyyy-MM-dd');
                let userId = sessionStorage('userId').getObject('userId').userId;
                let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                this.form1datacopy.endDate = this.formatDate(new Date(this.form1datacopy.endDate), 'yyyy-MM-dd');
                if (this.file!=null){
                    const file = this.file;
                    let formData = new FormData();
                    formData.append("file", file);
                    this.$http.put(Api.uploadMongoFile, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.form1datacopy.programmeFile = res.data.id;
                        if(this.add){

                            this.form1datacopy.staff = userId;
                            this.form1datacopy.createUserId = userId;
                            this.form1datacopy.createOrgId = orgId;
                            this.$http.post(Api.saveProgramme, this.form1datacopy).then((res) => {
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }else{
                            this.form1datacopy.updateUserId = userId;
                            this.form1datacopy.updateOrgId = orgId;
                            this.$http.post(Api.updateProgramme, this.form1datacopy).then((res) => {
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }
                    } else {
                        this.$Message.error("附件上传失败");
                    }
                    }).catch(e => {
                        this.model1 = false;
                        this.query();
                        this.$Message.error("数据获取失败")
                    })
                }else{
                    if(this.add) {
                        this.form1datacopy.createUserId = userId;
                        this.form1datacopy.createOrgId = orgId;
                        this.$http.post(Api.saveProgramme, this.form1datacopy).then((res) => {
                            this.$Message.success("保存成功")
                            this.model1 = false;
                            this.query();

                        }).catch(e => {
                            this.model1 = false;
                            this.query();
                            this.$Message.error("数据获取失败")
                        })
                    }else{
                        this.form1datacopy.updateUserId = userId;
                        this.form1datacopy.updateOrgId = orgId;
                        this.$http.post(Api.updateProgramme, this.form1datacopy).then((res) => {
                            this.$Message.success("保存成功")
                            this.model1 = false;
                            this.query();

                        }).catch(e => {
                            this.model1 = false;
                            this.query();
                            this.$Message.error("数据获取失败")
                        })
                    }
                }
            } else {
                this.$Message.error('请填报完整!');
            }
        })
    },*/
    submit(name) {

      this.$refs[name].validate((valid) => {
        if (valid) {
          this.saveMod = true;
          this.buttonLoading = true;
          this.form1datacopy.startDate = this.formatDate(new Date(this.form1datacopy.startDate), 'yyyy-MM-dd');
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
          this.form1datacopy.activityType = this.$route.query.type;
          this.form1datacopy.endDate = this.formatDate(new Date(this.form1datacopy.endDate), 'yyyy-MM-dd');
          if (this.add) {
            this.form1datacopy.staff = userId;
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.$http.post(Api.saveProgramme, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.model1 = false;
              this.saveMod = false;
              this.query();
              this.buttonLoading = false;
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
            // this.$Message.success("提交成功请勿重复提交")
          } else {
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateProgramme, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.saveMod = false;
              this.model1 = false;
              this.query();
              this.buttonLoading = false;
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          }
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    addInfo() {
      this.title = "活动方案新增";
      this.saveMod = false;
      let orgName = sessionStorage('userId').getObject('userId').orgInfo.orgName;
      let userId = sessionStorage('userId').getObject('userId').userId;
      let userName = sessionStorage('userId').getObject('userId').userName;
      this.form1datacopy = {
        themeAddress: orgName,
        staff: userId,
        staffName: userName,

      };
      this.setStaff = {
        value: userId,
        label: userName
      };
      this.setAuditor = {};
      this.setApprovedBy = {};
      this.peportingUnitId = '';
      this.peportingUnitName = '';
      this.coverName = null;
      this.fileName = null;
      this.add = true;
      this.model1 = true;
    },
    submitActivity(data) {
      // let istrue = confirm("是否确认提交该条活动方案？");
      // if (istrue) {
      this.loading = true;
      var params = {}
      params.key = "SafetyCampaign"
      params.formKey = "programmeForApproval"
      params.type = "hdfa"
      params.workId = data.row.programmeId
      params.createUserId = sessionStorage("userId").getObject("userId").userId;
      params.userName = sessionStorage("userId").getObject("userId").userName
      params.nextUserId = data.row.auditor
      params.threeUserId = data.row.approvedBy
      let userId = sessionStorage('userId').getObject('userId').userId;
      let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
      let programme = {
        programmeId: data.row.programmeId,
        reportingUnit: orgId,
        reportingDate: new Date(),
        updateUserId: userId,
        updateOrgId: orgId,
      };
      console.log(Api.submit);
      this.$http.post(Api.submit, params).then((res) => {
        this.$Message.success("提交成功")
        this.$http.post(Api.updateProgramme, programme).then((res) => {
          this.query();
          this.loading = false;
        }).catch(e => {
          this.query();
          this.loading = false;
        })
      }).catch(e => {
        this.query();
        this.loading = false;
        this.$Message.error("数据获取失败")
      })
      // }
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  },
  /* watch: {
       "model1": function (qw, er) {
           if (qw && this.model1) {
               setTimeout(() => {
                   this.$refs.childAuditor.setCurrentUser();
                   this.$refs.childapprovedBy.setCurrentUser();
                   this.$refs.childStaff.setCurrentUser();

               }, 100)
           } else {
               this.$refs.childAuditor.setCurrentUser();
               this.$refs.childapprovedBy.setCurrentUser();
               this.$refs.childStaff.setCurrentUser();
           }
       }
   }*/
}
</script>
<style lang='css' scoped>
@import '../../../../index.css';
</style>
